package config

import (
	"io/ioutil"
	"os"

	"github.com/go-kit/kit/log"
	toml "github.com/pelletier/go-toml"
)

// ConfigFile 服务配置对象定义
type ConfigFile struct {
	Common *CommonConfig `toml:"common"`
	GRPC   *GRPCConfig   `toml:"grpc"`
	HTTP   *HTTPConfig   `toml:"http"`
}

// CommonConfig 服务通用配置部分
type CommonConfig struct {
	SvcName        string `toml:"svc-name"`
	ListenHost     string `toml:"listen-host"`
	DebugPort      string `toml:"debug-port"`
	SRDETCDServers string `toml:"srd-etcd-servers"`
	SRDETCDCaCert  string `toml:"srd-etcd-ca-cert"`
	SRDETCDCert    string `toml:"srd-etcd-cert"`
	SRDETCDKey     string `toml:"srd-etcd-key"`
	SRDPrefix      string `toml:"srd-prefix"`
	RateLimit      int    `toml:"rate-limit"`
}

// GRPCConfig GRPC配置部分
type GRPCConfig struct {
	GRPCPort string `toml:"grpc-port"`
}

// HTTPConfig HTTP配置部分
type HTTPConfig struct {
	HTTPPort string `toml:"http-port"`
}

// ParseConfigFile 解析配置文件方法
func ParseConfigFile(filePath string, logger log.Logger) *ConfigFile {
	var conf ConfigFile
	fs, err := ioutil.ReadFile(filePath)
	if err != nil {
		logger.Log("config file with TOML format not found", err)
		os.Exit(1)
	}
	if err := toml.Unmarshal(fs, &conf); err != nil {
		logger.Log("config file with TOML format parse fail", err)
		os.Exit(1)
	}
	return &conf
}
